package com.zimin.common.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.zimin.common.constant.ServletConstant;
import com.zimin.common.constant.StringPool;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;


/**
 * 客户端 工具类
 *
 * @author : zimin
 * @since : 2022/06/04
 */
public class ServletUtil {

    /**
     * 获取当前请求URL
     */
    public static String getPath() {
        try {
            return getRequestAttributes().getRequest().getRequestURI();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取当前用户名称
     */
    public static String getUserName() {
        try {
            return Convert.toStr(urlEncode(getRequest().getHeader(ServletConstant.USER_NAME)));
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取当前用户邮箱
     */
    public static String getUserMail() {
        try {
            return Convert.toStr(getRequest().getHeader(ServletConstant.USER_MAIL));
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取当前用户ID
     */
    public static String getUserId() {
        try {
            return getRequest().getHeader(ServletConstant.USER_ID);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取当前用户菜单权限
     */
    @Deprecated
    public static List<String> getMenuPermissions() {
        try {
            return getHeaderParams(ServletConstant.MENU_PERMISSIONS);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取当前用户角色权限
     */
    @Deprecated
    public static List<String> getRolePermissions() {
        try {
            return getHeaderParams(ServletConstant.ROLE_PERMISSIONS);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取当前IP地址
     */
    public static String getIp() {
        try {
            return cn.hutool.extra.servlet.ServletUtil.getClientIP(ServletUtil.getRequest());
        } catch (Exception e) {
            return ServletConstant.DEFAULT_IP;
        }
    }

    /**
     * 获取当前用户Token
     */
    public static String getToken(ServerHttpRequest request) {
        String authorization = request.getHeaders().getFirst(ServletConstant.AUTHORIZATION);
        if (StrUtil.isNotEmpty(authorization) && authorization.startsWith(ServletConstant.TOKEN_PREFIX)) {
            return authorization.replace(ServletConstant.TOKEN_PREFIX, StringPool.EMPTY);
        }
        return null;
    }

    /**
     * 获取当前用户Token
     */
    public static String getToken() {
        try {
            String authorization = getRequest().getHeader(ServletConstant.AUTHORIZATION);
            if (StrUtil.isNotEmpty(authorization) && authorization.startsWith(ServletConstant.TOKEN_PREFIX)) {
                return authorization.replace(ServletConstant.TOKEN_PREFIX, StringPool.EMPTY);
            }
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * 获取当前请求所有消息头参数
     */
    public static Map<String, String> getHeaders() {
        try {
            return cn.hutool.extra.servlet.ServletUtil.getHeaderMap(ServletUtil.getRequest());
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取当前请求指定消息头参数
     */
    public static List<String> getHeaderParams(String name) {
        return StringUtils.split(StrUtil.strip(getRequest().getHeader(name), StrUtil.BRACKET_START,
                StrUtil.BRACKET_END));
    }

    /**
     * 获取当前请求指定请求参数
     */
    public static List<String> getRequestParams(String name) {
        return StringUtils.split(getRequest().getParameter(name));
    }

    /**
     * 指定请求参数编码
     */
    public static String urlEncode(String str) throws Exception {
        return java.net.URLEncoder.encode(str, StandardCharsets.UTF_8);
    }

    /**
     * 指定请求参数解码
     */
    public static String urlDecode(String str) throws Exception {
        return URLDecoder.decode(str, StandardCharsets.UTF_8);
    }

    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();

    }

    public static String getBrowser(HttpServletRequest request) {
        String type = "ie";
        String browserName = request.getHeader("USER-AGENT").toLowerCase();
        if (browserName.indexOf("msie") > 0) {
            type = "ie";
        }

        if (browserName.indexOf("firefox") > 0) {
            type = "firefox";
        }
        if (browserName.indexOf("chrome") > 0) {
            type = "chrome";
        }

        if (browserName.indexOf("opera") > 0) {
            type = "opera";
        }
        if (browserName.indexOf("gecko") > 0 && browserName.indexOf("rv:11") > 0) {
            type = "ie11";
        }
        return type;
    }

    public static HttpServletResponse getResponse() {
        return getRequestAttributes().getResponse();

    }

    public static ServletRequestAttributes getRequestAttributes() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }


    /**
     * 获取请求来源IP地址
     *
     * @param request HttpServletRequest
     * @return 返回 IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if ((ipAddress == null) || (ipAddress.length() == 0) || ("unknown".equalsIgnoreCase(ipAddress))) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if ((ipAddress == null) || (ipAddress.length() == 0) || ("unknown".equalsIgnoreCase(ipAddress))) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if ((ipAddress == null) || (ipAddress.length() == 0) || ("unknown".equalsIgnoreCase(ipAddress))) {
            ipAddress = getRemoteAddr(request.getRemoteAddr());
        }

        if ((ipAddress != null) && (ipAddress.length() > 15)) {
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

    private static String getRemoteAddr(String remoteAddr) {
        if (ServletConstant.DEFAULT_IP.equals(remoteAddr)) {
            InetAddress inet = null;
            try {
                inet = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            remoteAddr = inet.getHostAddress();
        }
        return remoteAddr;
    }


    /**
     * 判断是不是Ajax请求
     *
     * @param request HttpServletRequest
     * @return true是，false不是
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String her = request.getHeader("X-Requested-With");
        if (StringUtils.isNotEmpty(her)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }


}
